package cn.CommonUtils;

import org.ehcache.CacheManager;
import org.ehcache.Status;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

import javax.annotation.Resource;
import java.net.URL;

//  双锁单例ehcache工厂
public class EhcacheFactory {

    private static volatile CacheManager cacheManager;
    private EhcacheFactory(){}

    public static synchronized CacheManager getCacheManager(){
        if(cacheManager!=null){
            return cacheManager;
        }else{
            ProtectedInstance protectedInstance = new ProtectedInstance();
            cacheManager = protectedInstance.getCachaManager();
        }
        return cacheManager;
    }

    public static synchronized CacheManager getCacheManager(boolean hasAvailable){
        if(hasAvailable){
        CacheManager cm = getCacheManager();
            if (cm != null && cm.getStatus() != Status.AVAILABLE) {
                cm.init();
            }
        }
        return cacheManager;
    }
}

class ProtectedInstance{
    public CacheManager getCachaManager(){
        Configuration configuration = new XmlConfiguration(this.getClass().getResource("/ehcache.xml"));
        CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
        return cacheManager;
    }

    public ProtectedInstance() {
    }
}
